package com.keai.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.keai.pojo.Permission;
import com.keai.pojo.Role;
import com.keai.pojo.SysUser;
import com.keai.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class SecurityConfigUserService implements UserDetailsService {

    @Reference
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        SysUser sysUser = userService.findByUsername(username);
        if (sysUser == null){
            return null;
        }

//        创建权限集合对象
        List<GrantedAuthority> authorityList = new ArrayList<>();
//        遍历用户对应的角色
        for (Role role : sysUser.getRoles()) {
//            每个角色对应的权限
            for (Permission permission : role.getPermissions()) {
                String keyword = permission.getKeyword();
//                创建权限对象
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(keyword);
//                把权限对象添加到集合中
                authorityList.add(authority);
            }
        }

        User user =new User(sysUser.getUsername(),sysUser.getPassword(),authorityList);

        return user;
    }
}
